package com.cy.pj.ajax.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
public class AjaxController {

    private List<Map<String,Object>> data =new ArrayList<>();
    public AjaxController(){
        Map<String,Object> map = new HashMap<>();
        map.put("id","100");
        map.put("name","huawei");
        map.put("remark","Very Good");
        data.add(map);
    }

    @PutMapping("/doAjaxPut")
    @ResponseBody
    public String doAjaxUpdate(@RequestParam Map<String,Object> map){
        String id = (String)map.get("id");
        Iterator<Map<String, Object>> it = data.iterator();
        Map<String,Object> obj = null;
        while (it.hasNext()){
            obj=it.next();
            if (obj.get("id").equals(id))
                break;
            }
            obj.put("name",map.get("name"));
            obj.put("remark",map.get("remark"));
        return "update ok";
    }
    @DeleteMapping("/doAjaxDelete")
    @ResponseBody
    public String doAjaxDelete(String id){
        Iterator it = data.iterator();
        while(it.hasNext()){
            Map<String,Object> map =(Map<String,Object>) it.next();
            if(map.get("id").equals(id)){
                it.remove();
            }
        }
        return "delete ok";
    }

    @PostMapping("/doAjaxPost")
    @ResponseBody
    public  String doAjaxPost(@RequestParam Map<String,Object> map){
        data.add(map);
        return "save ok";
    }
    //
    @GetMapping("/doAjaxGet")
    @ResponseBody
    public List<Map<String,Object>> doAjaxGet(){
        return data;
    }

    @RequestMapping("/doNotAjaxUI")
    public String doNotAjaxUI(){
        return "not-ajax-01";
    }

    @RequestMapping("/doNotAjaxStart")
    public String doNotAjaxStart(Model model){
        model.addAttribute("result","do not ajax request result");
        return "not-ajax-01";
    }

    @RequestMapping("/doAjaxStart")
    @ResponseBody
    public String  doAjaxStart() throws InterruptedException {
        Thread.sleep(5000);
        return "Response Result Of Ajax Get Request o1";
    }
}
